package com.ym.wcp.framework.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Map;

public class JsonUtil {
    private static final ObjectMapper om;

    static {
        om = new ObjectMapper();
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * 对象转JSON
     */
    public static String objectToJson(Object object) {
        try {
            return om.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * JSON转对象
     */
    public static <T> T jsonToObject(String json, Class<T> valueType) throws IOException {
        return om.readValue(json, valueType);
    }

    /**
     * JSON转对象集合
     */
    public static <T> T jsonToObject(String json, TypeReference<?> valueTypeRef) throws IOException {
        return om.readValue(json, valueTypeRef);
    }

    // 将Map转成指定的Bean
    public static <T> T mapToBean(Map map, TypeReference<T> valueTypeRef) throws Exception {
        return om.readValue(objectToJson(map), valueTypeRef);
    }

    public static <T> T mapToBean(Map map, Class<T> cls) throws Exception {
        return om.readValue(objectToJson(map), cls);
    }


    // 将Bean转成Map
    public static Map beanToMap(Object obj) throws Exception {
        return om.readValue(objectToJson(obj), Map.class);
    }

    // 将Bean转成Object
    public static <T> T beanToObject(Object obj, Class<T> cls) throws Exception {
        return om.readValue(objectToJson(obj), cls);
    }

    public static ObjectMapper getJackson() {
        return om;
    }
}
